﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TagLib;

namespace LibraryToCSV
{
    public class FileIO
    {
        private DirectoryInfo directorySource;
        private DirectoryInfo directoryTarget;
        private List<TagLib.File> songList = new List<TagLib.File>();

        public FileIO(string dirSource, string dirTarget)
        {
            directorySource = new DirectoryInfo(dirSource);
            directoryTarget = new DirectoryInfo(dirTarget);
        }

        public void Read()
        {
            foreach (DirectoryInfo dir in directorySource.GetDirectories("*.*", SearchOption.AllDirectories))
            {
                ReadFolderContent(dir);
            }
            WriteCSV();
        }

        private bool CheckContainFolders(DirectoryInfo dir)
        {
            if (dir.GetDirectories().Length > 0) return true;
            else return false;
        }

        private void ReadFolderContent(DirectoryInfo dir)
        {
            var audioFiles = (from mp3 in dir.GetFiles()
                              where mp3.Extension == ".mp3" || mp3.Extension == ".wma"
                              select mp3);
            var test = dir.GetFiles();

            foreach (var item in audioFiles)
            {
                songList.Add(TagLib.File.Create(item.FullName));
            }
        }

        private void WriteCSV()
        {
            var fileName = "output.csv";
            StreamWriter writer = new StreamWriter(directoryTarget.FullName + "\\" + fileName);
            writer.WriteLine("Artist,Title,Album,Album Artist");
            foreach (var item in songList)
            {
                writer.WriteLine('"' 
                    + String.Join("", item.Tag.Performers)
                    + '"' 
                    + ',' 
                    + '"' 
                    + item.Tag.Title
                    + '"' 
                    + ','
                    + '"' 
                    + item.Tag.Album
                    + '"' 
                    + ','
                    + '"' 
                    + String.Join("", item.Tag.AlbumArtists)
                    + '"');
            }
            writer.Close();
        }
    }
}